//
//  SetViewController.m
//  easystudy
//
//  Created by 七 on 16/9/4.
//  Copyright © 2016年 kane. All rights reserved.
//

#import "SetViewController.h"
#import "ReleatedController.h"
#import "OutlineDownloadController.h"
#import "SuggestController.h"
#import "AboutController.h"
#import "RecommendController.h"
#import "LoginAndRegistController.h"
#import "Reachability.h"
#import "FondViewController.h"
@interface SetViewController ()<UITableViewDelegate,UITableViewDataSource,UIAlertViewDelegate>
{
    __weak IBOutlet UITableView *setTable;
    
    IBOutlet UIView *BGView;
    __weak IBOutlet UILabel *lineLbl;
    __weak IBOutlet UIView *navView;
    __weak IBOutlet UILabel *titleLbl;
}
@property (nonatomic, strong) Reachability *conn;
@end

@implementation SetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkStateChange) name:kReachabilityChangedNotification object:nil];
    self.conn = [Reachability reachabilityForInternetConnection];
    [self.conn startNotifier];
    setTable.backgroundColor = KKColor_DarkWhite_Black;
    BGView.backgroundColor = KKColor_BGColor_GrayToDarkgray;
    lineLbl.backgroundColor = KKColor_NavLineColor;
    navView.backgroundColor = KKColor_DarkGray_White;
    titleLbl.textColor = KKColor_Black_LightGary;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeFont) name:@"fontChange" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [setTable reloadData];
}

- (void)changeFont
{
    [setTable reloadData];
}

#pragma mark - User Action
- (IBAction)backPress:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


- (long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//遍历文件夹获得文件夹大小，返回多少M

- (float ) folderSizeAtPath:(NSString*) folderPath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    NSString* fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}

- (void)networkStateChange{
     Reachability *conn = [Reachability reachabilityForInternetConnection];
    [[NSUserDefaults standardUserDefaults] setObject:@([conn currentReachabilityStatus]) forKey:@"NetworkState"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)NoImageMode:(UISwitch *)sender {
    if (sender.on) {
        if (NetStatus == ReachableViaWWAN) {
            [[NSUserDefaults standardUserDefaults] setObject:@(NO) forKey:@"ShowImage"];
        }else{
            [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"ShowImage"];
        }
    }else{
        [[NSUserDefaults standardUserDefaults] setObject:@(YES) forKey:@"ShowImage"];
    }
}

#pragma mark - UITableView Delegate && DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 5;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    switch (section) {
        case 0:
        case 1:
            return 2;
            break;
        case 2:
        case 4:
            return 3;
        default:
            return 1;
            break;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identify = [NSString stringWithFormat:@"%ld%ld",(long)indexPath.section,(long)indexPath.row];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identify];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identify];
    }
    cell.textLabel.font = [UIFont systemFontOfSize:15];
    cell.backgroundColor = KKColor_DarkGray_White;
    cell.textLabel.textColor = KKColor_Black_LightGary;
    switch (indexPath.section) {
        case 0:{
            if (indexPath.row == 0) {
                UILabel *loginLbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 250, 60, 40)];
                cell.imageView.image = [UIImage imageNamed:@"setting_personal"];
                if ([UserEntity sharedUser].loginSuccess) {
                    cell.textLabel.text = [UserEntity sharedUser].NickName;
                    loginLbl.text = @"退出登录";
                }else{
                    cell.textLabel.text = @"访客";
                    loginLbl.text = @"点击登录";
                }
                loginLbl.textColor = [UIColor colorWithHex:0X46C09A];
                loginLbl.textAlignment = NSTextAlignmentRight;
                loginLbl.font = [UIFont systemFontOfSize:13];
                cell.accessoryView = loginLbl;
            }else{
                cell.imageView.image = [UIImage imageNamed:@"setting_bind"];
                cell.textLabel.text = @"绑定社交账号";
            }
        }break;
            case 1:
            if (indexPath.row == 0) {
                cell.imageView.image = [UIImage imageNamed:@"setting_offline"];
                cell.textLabel.text = @"离线下载管理";
            }else{
                cell.imageView.image = [UIImage imageNamed:@"setting_cache"];
                cell.textLabel.text = @"清理缓存";
                UILabel *clearLbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 250, 60, 40)];
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
                NSString *path = [paths lastObject];
                NSString *str = [NSString stringWithFormat:@"%.2fMB", [self folderSizeAtPath:path]];
                UIActivityIndicatorView *imgAnimate = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 270, 40, 40)];
                if (_isAnimate) {
                    cell.accessoryView = imgAnimate;
                    [imgAnimate startAnimating];
                    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:path];
                    for (NSString *p in files) {
                        NSError *error;
                        NSString *Path = [path stringByAppendingPathComponent:p];
                        if ([[NSFileManager defaultManager] fileExistsAtPath:Path]) {
                            [[NSFileManager defaultManager] removeItemAtPath:Path error:&error];
                        }
                    }
                    [imgAnimate stopAnimating];
                    NSString *str = [NSString stringWithFormat:@"%.2fMB", [self folderSizeAtPath:path]];
                    [clearLbl setText:str];
                    [clearLbl setTextColor:[UIColor colorWithHex:0X46C09A]];
                    clearLbl.textAlignment = NSTextAlignmentRight;
                    clearLbl.font = [UIFont systemFontOfSize:13];
                    cell.accessoryView = clearLbl;
                    _isAnimate = NO;
                }else{
                    [clearLbl setText:str];
                    [clearLbl setTextColor:[UIColor colorWithHex:0X46C09A]];
                    clearLbl.textAlignment = NSTextAlignmentRight;
                    clearLbl.font = [UIFont systemFontOfSize:13];
                    cell.accessoryView = clearLbl;
                }
            }break;
        case 2:{
            if (indexPath.row == 0) {
                cell.imageView.image = [UIImage imageNamed:@"setting_traffic"];
                cell.textLabel.text = @"2G/3G下无图模式";
                UISwitch *downloadSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
                [downloadSwitch addTarget:self action:@selector(NoImageMode:) forControlEvents:UIControlEventValueChanged];
                cell.accessoryView = downloadSwitch;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }else if(indexPath.row == 1){
                cell.imageView.image = [UIImage imageNamed:@"setting_font"];
                cell.textLabel.text = @"字体选择";
                UILabel *textFondLbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 250, 60, 40)];
                switch (FONT_SIZE) {
                    case 0:
                        [textFondLbl setText:@"小字体"];
                        break;
                    case 1:
                        [textFondLbl setText:@"中字体"];
                        break;
                    case 2:
                        [textFondLbl setText:@"大字体"];
                        break;
                    case 3:
                        [textFondLbl setText:@"超大字体"];
                        break;
                    default:
                        break;
                }
                [textFondLbl setTextColor:[UIColor colorWithHex:0X46C09A]];
                textFondLbl.textAlignment = NSTextAlignmentRight;
                textFondLbl.font = [UIFont systemFontOfSize:13];
                cell.accessoryView = textFondLbl;
            }else{
                cell.imageView.image = [UIImage imageNamed:@"setting_push"];
                cell.textLabel.text = @"通知推送";
                UISwitch *pushSwitch = [[UISwitch alloc] initWithFrame:CGRectZero];
                cell.accessoryView = pushSwitch;
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
        }break;
            case 3:
            cell.textLabel.text = @"推荐一点资讯给朋友";
            cell.imageView.image = [UIImage imageNamed:@"setting_recommend"];
            break;
            case 4:{
                if (indexPath.row == 0) {
                    cell.imageView.image = [UIImage imageNamed:@"setting_feedback"];
                    cell.textLabel.text = @"给健康养生题意见";
                }else if(indexPath.row == 1){
                    cell.imageView.image = [UIImage imageNamed:@"setting_score"];
                    cell.textLabel.text = @"为健康养生评分";
                }else{
                    cell.imageView.image = [UIImage imageNamed:@"setting_about"];
                    cell.textLabel.text = @"关于";
                }
            }break;
        default:
            break;
    }
    
    return cell;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.section) {
        case 0:{
            if (indexPath.row == 0) {
                if ([UserEntity sharedUser].loginSuccess) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"退出登录?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"退出", nil];
                    alert.delegate = self;
                    [alert show];
                }else{
                    LoginAndRegistController *loginVC = [[LoginAndRegistController alloc] init];
                    loginVC.isFromSetView = YES;
                    [self.navigationController pushViewController:loginVC animated:YES];
                }
            }else{
                ReleatedController *releatedVC = [[ReleatedController alloc] init];
                [self.navigationController pushViewController:releatedVC animated:YES];
            }
        }break;
        case 1:{
            if (indexPath.row == 0) {
                OutlineDownloadController *outlineDownloadVC = [[OutlineDownloadController alloc] init];
                [self.navigationController pushViewController:outlineDownloadVC animated:YES];
            }else{//清理缓存
                _isAnimate = YES;
                [setTable reloadData];
            }
        }break;
        case 2:{
            if (indexPath.row == 1){
                FondViewController *fontVC = [[FondViewController alloc] init];
                [self.navigationController pushViewController:fontVC animated:YES];
            }
        }break;
        case 3:{
            RecommendController *recommendVC = [[RecommendController alloc] init];
            [self.navigationController pushViewController:recommendVC animated:YES];
        }break;
        case 4:{
            if (indexPath.row == 0) {
                SuggestController *suggestVC = [[SuggestController alloc] init];
                [self.navigationController pushViewController:suggestVC animated:YES];
            }else if (indexPath.row == 1){
                
            }else{
                AboutController *aboutVC = [[AboutController alloc] init];
                [self.navigationController pushViewController:aboutVC animated:YES];
            }
         }break;
        default:
            break;
    }
    
}

#pragma mark - UIAlertView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == alertView.firstOtherButtonIndex) {
        [UserEntity sharedUser].loginSuccess = NO;
    }
}

@end
